//
//  TTAPI.swift
//  TTCOM
//
//  Created by Toj on 1/26/21.
//

import Foundation

public struct TTAPI {
    
    public struct Request {
        public static var prepareExecute:(()->())?
    }
}

extension TTAPI.Request {
    
    static
    func general<T>(api url: String,
                    model: T.Type,
                    type: TTHTTPRequestType = .post,
                    hearders: TTAPIRequest.Header? = nil,
                    parameters: [String: Any]? = nil,
                    prepare execute: (()->())? = nil,
                    completion: ((_ response:TTResponse<T>)->())?)
    where T: TTJSONCodable {
        
        let aPrepare = execute ?? prepareExecute
        aPrepare?()
        
        let aHearders = hearders ?? TTAPIRequest.Header.general
        var allParameters = parameters ?? [:]
        allParameters.t_merge(dict: TTAPIRequest.Parameters.base)
        
        TTHTTPServer.shared.request(api:url,
                                    model: model,
                                    hearders: aHearders.rawValue,
                                    parameters: allParameters)
        { (response) in
            // 数据异常/ 错误
            if  response.data == nil &&
                    response.message.count == 0 &&
                    response.code != .success {
                response.message = "数据异常, 请联系官方人员"
            }
            
            if response.code != .success {
                // alert
                print("alert : " + "\(response.code) : " + response.message)
            }
            completion?(response)
        }
    }
    
    static
    func general<T>(api url: TTAPIRequest.API,
                    model: T.Type,
                    type: TTHTTPRequestType = .post,
                    hearders: TTAPIRequest.Header? = nil,
                    parameters: [String: Any]? = nil,
                    prepare execute: (()->())? = nil,
                    completion: ((_ response:TTResponse<T>)->())?)
    where T: TTJSONCodable {
        
        let url = TTAPIRequest.API.base + url.rawValue
        general(api: url, model: model, type: type, hearders: hearders, parameters: parameters, prepare: execute, completion: completion)
    }
}

extension Dictionary {
    
    fileprivate mutating func t_merge(dict: Dictionary<Key,Value>) {
        for (key, value) in dict {
            self[key] = value
        }
    }
}
